package cc.eddic.practice.concurrency.impl;

import cc.eddic.practice.concurrency.LogItem;
import cc.eddic.practice.concurrency.LogParser;

import java.util.List;
import java.util.Map;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;

public class LogParserWithFuture2ScwImpl implements LogParser {
    private final int THREAD_POOL_SIZE = 128; // 线程池大小，根据需要进行调整

    @Override
    public Map<String, List<LogItem>> parse(String folderName) {
        Map<String, List<LogItem>> resultMap = new ConcurrentHashMap<>(); // 使用线程安全的 ConcurrentHashMap
        File fileFolder = new File(folderName);
        traverseFolder(fileFolder, resultMap);
        return resultMap;
    }

    private void traverseFolder(File fileFolder, Map<String, List<LogItem>> resultMap) {
        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
        File[] files = fileFolder.listFiles();
        if (files != null) {
            List<Future<Void>> futures = new ArrayList<>();
            for (File file : files) {
                if (file.isDirectory()) {
                        traverseFolder(file, resultMap);
                } else if (file.getName().endsWith(".log")) {
                    Future<Void> future = executorService.submit(() -> {
                        try {
                            List<LogItem> logItems = parseLogFile(file.getAbsolutePath());
                            resultMap.put(file.getAbsolutePath(), logItems);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        return null;
                    });
                    futures.add(future);
                }
            }

            // 等待所有任务完成
            for (Future<Void> future : futures) {
                try {
                    future.get();
                } catch (InterruptedException | ExecutionException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        executorService.shutdown();
    }

    private List<LogItem> parseLogFile(String path) throws IOException {
        List<LogItem> logItems = new ArrayList<>();
        LogItemParserScwImpl logItemParser = new LogItemParserScwImpl();
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            String line;
            while ((line = reader.readLine()) != null) {
                Optional<LogItem> parsedLogItem = logItemParser.parse(line);
                parsedLogItem.ifPresent(logItems::add);
            }
        }
        return logItems;
    }
}


